<?php
/**
 * 首页全屏广告 - 管理后台
 *
 * @author karl <karl.tang@aiyuangong.com>
 * @link http://www.aiyuangong.com
 */

namespace app\admin\controller\type;

use app\admin\controller\system\Item;
use think\Exception;
use think\Db;

class AdHomeFull extends Item
{
    protected $tag = 'ad_home_full';
    
    //层级
    protected $level = 1;
    
    protected $title = ['name' => '标题', 'tag' => '链接', 'remark' => '备注'];
    
    //列表字段
    protected $row  = ['id', 'name'];
    
    // 列表显示的按钮
    protected $extend_list_btns = [
        [
            'name' => '预览',
            'url' => 'preview',
            'type' => 'full_page',
            'icon' => '预览'
        ]
    ];
    
    /**
     * 添加
     * @return mixed
     */
    public function add() {
        if ($this->request->isPost()) {
            // 插入
            $data = $this->request->only('pid,name,tag,remark,sort,status', 'post');
            unset($data['id']);
            if ($this->level < 2 || !isset($data['pid'])) {
                $data['pid'] = $this->rootItem['id'];
            }

            $fields = \Fields::get_data($this->fields, 'post', $this->field_name, $this->field_type);
            if (!is_array($fields)) {
                throw new Exception((string) $fields ?: "未知错误");
            } else {
                $data['fields'] = json_encode($fields);
            }
            // 写入数据
            Db::startTrans();
            try {
                $model = Db::name($this->parseTable('type'));
                $data['id'] = $model->insertGetId($data);
                $js_path = ROOT_PATH . 'public' . $fields['indexjs'];
                $package_path = ROOT_PATH . 'public' . $fields['package'];
                if (file_exists($package_path)) {
                    $filename = explode('/', $package_path);
                    $filename = end($filename);
                    $target_path = ROOT_PATH . 'public/uploads/adv/' . $data['id'] . '/';
                    //判断目录是否存在，如果否，创建目录。  
                    if (!is_dir($target_path)) {
                        mkdir($target_path, 0777, TRUE);
                    }
                    if ($package_path == $target_path . $filename) {
                        $result = true;
                    } else {
                        $result = copy($package_path, $target_path . $filename);
                        if ($result) {
                            $result = unzip($target_path . $filename, $target_path); //解压缩文件夹到广告目录下
                            if (!$result) {
                                throw new Exception('解压缩失败');
                            }
                            $fields['package'] = '/uploads/adv/' . $data['id'] . '/' . $filename;
                            unlink($package_path);
                        } else {
                            throw new Exception('广告包拷贝出错');
                        }
                    }
                }
                if (file_exists($js_path)) {
                    $filename = explode('/', $js_path);
                    $filename = end($filename);
                    $target_path = ROOT_PATH . 'public/uploads/adv/' . $data['id'] . '/';
                    //判断目录是否存在，如果否，创建目录。  
                    if (!is_dir($target_path)) {
                        mkdir($target_path, 0777, TRUE);
                    }

                    if ($js_path == $target_path . $filename) {
                        $result = true;
                    } else {
                        $result = copy($js_path, $target_path . $filename); //复制js文件到广告文件夹下，覆盖
                        if ($result) {
                            $fields['indexjs'] = '/uploads/adv/' . $data['id'] . '/' . $filename;
                            unlink($js_path);
                        } else {
                            throw new Exception('脚本拷贝出错');
                        }
                    }
                }
                $data['fields'] = json_encode($fields);
                $model = Db::name($this->parseTable('type'));
                $ret = $model->where('id', $data['id'])->update($data);
                // 提交事务
                Db::commit();

                \Fields::clearCache();
                return ajax_return_adv('添加成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();

                return ajax_return_adv_error($e->getMessage());
            }
        } else {
            // 添加
            if ($this->level > 1) {
                $parent = Db::name("type")->where(['pid' => $this->rootItem['id'], 'isdelete' => 0])->column("name", "id");
                $this->view->assign("parent", $parent);
            }
            $this->view->assign("pid", $this->rootItem['id']);
            $this->view->assign("config", ['tpl' => $this->form_tpl, 'type' => $this->field_type, 'name' => $this->field_name]);
            $this->view->assign("title", $this->title);
            $this->view->assign("level", $this->level);
            $this->view->assign("fields", $this->fields);
            $this->view->assign("vo", ['pid' => 0]);
            return $this->view->fetch('system/item/edit');
        }
    }

    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        $controller = 'type';
        $module = $this->request->module();

        if ($this->request->isAjax()) {
            // 更新
            $data = $this->request->only('id,pid,name,tag,remark,sort,status,indexjs,package', 'post');
            if (!$data['id']) {
                return ajax_return_adv_error("缺少参数ID");
            } else if ($this->level < 2 || !isset($data['pid'])) {
                $data['pid'] = $this->rootItem['id'];
            }

            $fields = \Fields::get_data($this->fields, 'post', $this->field_name, $this->field_type);
            if (!is_array($fields)) {
                throw new Exception((string)$fields ? : "未知错误");
            }
            $js_path = ROOT_PATH.'public'.$fields['indexjs'];
            $package_path = ROOT_PATH.'public'.$fields['package'];
            if(file_exists($package_path)){
                $filename = explode('/',$package_path);
                $filename = end($filename);
                $target_path = ROOT_PATH.'public/uploads/adv/'.$data['id'].'/';
                //判断目录是否存在，如果否，创建目录。  
                if (!is_dir($target_path)) {
                    mkdir($target_path, 0777, TRUE);
                }
                if($package_path == $target_path.$filename){
                    $result = true;
                }else{
                    $result = copy($package_path,$target_path.$filename);
                    if($result){
                        $result = unzip($target_path.$filename, $target_path);//解压缩文件夹到广告目录下
                        if(!$result){
                            throw new Exception('解压缩失败');
                        }
                        $fields['package'] = '/uploads/adv/'.$data['id'].'/'.$filename;
                        unlink($package_path);
                    }else{
                        throw new Exception('广告包拷贝出错');
                    }
                }
                
            }
            if(file_exists($js_path)){
                $filename = explode('/',$js_path);
                $filename = end($filename);
                $target_path = ROOT_PATH.'public/uploads/adv/'.$data['id'].'/';
                //判断目录是否存在，如果否，创建目录。  
                if (!is_dir($target_path)) {
                    mkdir($target_path, 0777, TRUE);
                }
                
                if($js_path == $target_path.$filename){
                    $result = true;
                }else{
                    $result = copy($js_path,$target_path.$filename);//复制js文件到广告文件夹下，覆盖
                    if($result){
                        $fields['indexjs'] = '/uploads/adv/'.$data['id'].'/'.$filename;
                        unlink($js_path);
                    }else{
                        throw new Exception('脚本拷贝出错');
                    }
                }
                
            }
            $data['fields'] = json_encode($fields);
            // 更新数据
            Db::startTrans();
            try {
                // 简单的直接使用db更新
                $model = Db::name($this->parseTable($controller));
                $ret = $model->where('id', $data['id'])->update($data);
                // 提交事务
                Db::commit();

                \Fields::clearCache();
                return ajax_return_adv("编辑成功");
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();

                return ajax_return_adv_error($e->getMessage());
            } 
        } else {
            // 编辑
            $id = $this->request->param('id');
            if (!$id) {
                throw new Exception("缺少参数ID");
            }
            $vo = $this->getModel('type')->find($id);
            if (!$vo) {
                throw new HttpException(404, '该记录不存在');
            }
            
            if ($this->level > 1) {
                $parent = Db::name("type")->where(['pid' => $this->rootItem['id'], 'isdelete'=>0])->column("name", "id");
                $this->view->assign("parent", $parent);
            }
            $values = json_decode($vo['fields'], true);
            $this->view->assign("values", $values);
            
            $this->view->assign("vo", $vo);
            $this->view->assign("pid", $this->rootItem['id']);
            $this->view->assign("config", ['tpl'=>$this->form_tpl, 'type'=>$this->field_type, 'name'=>$this->field_name]);
            $this->view->assign("title", $this->title);
            $this->view->assign("level", $this->level);
            $this->view->assign("fields", $this->fields);
            return $this->view->fetch('system/item/edit');
        }
    }
    
     /**
     * 预览
     * @return mixed
     */
    public function preview(){
        $id = $this->request->param('id/d',0);
        $adv = \Fields::get_tree_data('ad_home_full', false);
        $adv = reset_by_key($adv['_child'], 'id');
        $adv = $adv[$id];
        $adv = json_decode($adv['fields'],true);
        if(!empty($adv))
            return '<script src="/old/data/resource/js/jquery.js"></script><script type="text/javascript">var AD_FULL_ID = '.$id.'</script><script type="text/javascript" src="'.$adv['indexjs'].'" charset="utf-8"></script>';
    }
}